package cn.vendsystem.com.utils;


import io.minio.*;
import io.minio.http.Method;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class MinioUtil {

    private final MinioClient minioClient;

    @Value("${minio.bucket}")
    private String bucketName;

    /**
     * 上传文件并返回可访问URL
     *
     * @param inputStream 文件输入流
     * @param size        文件大小
     * @param contentType 文件类型
     * @param originalFilename 原始文件名
     * @return 可访问URL
     */
    public String uploadFile(InputStream inputStream, long size, String contentType, String originalFilename) {
        try {
            // 按年月日生成目录
            String folder = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
            // 使用UUID生成随机文件名
            String suffix = originalFilename.contains(".") ?
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
            String objectName = folder + "/" + UUID.randomUUID() + suffix;

            // 上传
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .stream(inputStream, size, -1)  // size 必须指定
                            .contentType(contentType)
                            .build()
            );

            // 返回7天有效预签名URL
            return minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(bucketName)
                            .object(objectName)
                            .expiry(7, TimeUnit.DAYS)
                            .build()
            );
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败：" + e.getMessage(), e);
        }
    }

    /**
     * 删除文件
     *
     * @param objectName 对象名
     */
    public void deleteFile(String objectName) {
        try {
            minioClient.removeObject(
                    RemoveObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .build()
            );
        } catch (Exception e) {
            throw new RuntimeException("删除文件失败：" + e.getMessage(), e);
        }
    }
}
